// MongoDB用户管理工具 - 主要JavaScript文件

// 全局变量
var roleCounter = 0;
var editRoleCounter = 0;
var currentEditUser = null;
var currentEditConnectionId = null;

// 切换标签页
function switchTab(tabName) {
    // 隐藏所有标签内容
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
    });

    // 移除所有标签的active类
    document.querySelectorAll('.tab').forEach(tab => {
        tab.classList.remove('active');
    });

    // 显示选中的标签内容
    document.getElementById(tabName + '-tab').classList.add('active');

    // 添加active类到选中的标签
    event.target.classList.add('active');
}

// 清空用户管理和数据库列表内容
function clearDataDisplays() {
    // 清空用户列表
    const usersContent = document.getElementById('usersContent');
    if (usersContent) {
        usersContent.innerHTML = '<div class="loading">请先测试连接，然后点击"刷新用户列表"加载数据</div>';
    }

    // 清空数据库列表
    const databasesContent = document.getElementById('databasesContent');
    if (databasesContent) {
        databasesContent.innerHTML = '<div class="loading">请先测试连接，然后点击"刷新数据库列表"加载数据</div>';
    }

    // 清空数据库选择框
    const databaseSelect = document.getElementById('databaseSelect');
    if (databaseSelect) {
        databaseSelect.innerHTML = '<option value="">所有数据库</option>';
    }
}

// 测试连接
async function testConnection() {
    const btn = document.getElementById('testConnectionBtn');
    const statusIndicator = document.getElementById('connectionStatus');
    const statusText = document.getElementById('connectionText');
    const messageDiv = document.getElementById('connectionMessage');
    const environmentDiv = document.getElementById('currentEnvironment');
    const connectionSelect = document.getElementById('connectionSelect');

    const selectedConnectionId = connectionSelect.value;
    const originalBtnText = btn.textContent;

    // 清空之前的数据显示，避免用户混淆
    clearDataDisplays();

    btn.disabled = true;
    btn.textContent = '连接中...';
    statusText.textContent = '连接中...';
    environmentDiv.textContent = '';

    try {
        let response;

        if (selectedConnectionId) {
            // 测试选中的特定连接
            console.log(`测试选中的连接 ID: ${selectedConnectionId}`);
            response = await fetch(`/api/mongo-connections/${selectedConnectionId}/test`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        } else {
            // 测试当前活跃的连接
            console.log('测试当前活跃的连接');
            response = await fetch('/api/connection/test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        }

        const result = await response.json();

        if (result.status === 'success') {
            statusIndicator.className = 'status-indicator connected';
            statusText.textContent = '已连接';

            let successMessage = 'MongoDB连接成功！';
            if (result.server_info) {
                successMessage += `<br>版本: ${result.server_info.version}`;
                if (result.server_info.os) {
                    successMessage += `<br>系统: ${result.server_info.os}`;
                }
                successMessage += `<br>数据库数量: ${result.server_info.databases_count}`;
            }

            messageDiv.innerHTML = `<div class="success">${successMessage}</div>`;

            // 如果测试的是当前活跃连接，获取环境信息
            if (!selectedConnectionId) {
                await loadCurrentEnvironment();
            } else {
                // 显示测试的连接信息
                const selectedOption = connectionSelect.options[connectionSelect.selectedIndex];
                environmentDiv.textContent = `测试连接: ${selectedOption.textContent}`;
            }
        } else {
            statusIndicator.className = 'status-indicator disconnected';
            statusText.textContent = '连接失败';
            messageDiv.innerHTML = `<div class="error">连接失败: ${result.message}</div>`;
            environmentDiv.textContent = '';
        }
    } catch (error) {
        statusIndicator.className = 'status-indicator disconnected';
        statusText.textContent = '连接失败';
        messageDiv.innerHTML = `<div class="error">连接错误: ${error.message}</div>`;
        environmentDiv.textContent = '';
    }

    btn.disabled = false;
    btn.textContent = originalBtnText;
}

// 加载当前环境信息
async function loadCurrentEnvironment() {
    const environmentDiv = document.getElementById('currentEnvironment');

    try {
        const response = await fetch('/api/current-environment');
        const result = await response.json();

        if (response.ok && result.environment) {
            environmentDiv.textContent = `当前环境: ${result.environment.name} (${result.environment.host}:${result.environment.port})`;
        } else {
            environmentDiv.textContent = '无法获取环境信息';
        }
    } catch (error) {
        console.error('获取环境信息失败:', error);
        environmentDiv.textContent = '';
    }
}

// 加载用户列表
async function loadUsers() {
    const contentDiv = document.getElementById('usersContent');
    contentDiv.innerHTML = '<div class="loading">加载中...</div>';

    // 获取选中的连接ID
    const connectionSelect = document.getElementById('connectionSelect');
    const selectedConnectionId = connectionSelect.value;

    // 同时加载数据库列表到选择框
    await loadDatabaseOptions();

    try {
        // 构建URL，如果有选中的连接ID则添加参数
        let url = '/api/users';
        if (selectedConnectionId) {
            url += `?connection_id=${selectedConnectionId}`;
            console.log(`使用选中的连接 ID: ${selectedConnectionId} 获取用户列表`);
        } else {
            console.log('使用当前活跃连接获取用户列表');
        }

        const response = await fetch(url);
        const result = await response.json();

        if (response.ok && result.users) {
            displayUsers(result.users);
        } else {
            contentDiv.innerHTML = `<div class="error">加载失败: ${result.error || '未知错误'}</div>`;
        }
    } catch (error) {
        contentDiv.innerHTML = `<div class="error">请求失败: ${error.message}</div>`;
    }
}

// 根据选择的数据库加载用户
async function loadUsersByDatabase() {
    const selectedDatabase = document.getElementById('databaseSelect').value;
    const connectionSelect = document.getElementById('connectionSelect');
    const selectedConnectionId = connectionSelect.value;
    const contentDiv = document.getElementById('usersContent');
    contentDiv.innerHTML = '<div class="loading">加载中...</div>';

    try {
        // 构建URL参数
        const params = new URLSearchParams();
        if (selectedDatabase) {
            params.append('database', selectedDatabase);
        }
        if (selectedConnectionId) {
            params.append('connection_id', selectedConnectionId);
            console.log(`使用选中的连接 ID: ${selectedConnectionId} 获取数据库 '${selectedDatabase || '全部'}' 的用户`);
        } else {
            console.log(`使用当前活跃连接获取数据库 '${selectedDatabase || '全部'}' 的用户`);
        }

        const url = `/api/users${params.toString() ? '?' + params.toString() : ''}`;
        const response = await fetch(url);
        const result = await response.json();

        if (response.ok && result.users) {
            displayUsers(result.users);
        } else {
            contentDiv.innerHTML = `<div class="error">加载失败: ${result.error || '未知错误'}</div>`;
        }
    } catch (error) {
        contentDiv.innerHTML = `<div class="error">请求失败: ${error.message}</div>`;
    }
}

// 显示用户列表
function displayUsers(users) {
    const contentDiv = document.getElementById('usersContent');

    if (users.length === 0) {
        contentDiv.innerHTML = '<div class="loading">没有找到用户</div>';
        return;
    }

    let tableHTML = `
        <table class="table">
            <thead>
                <tr>
                    <th>用户名</th>
                    <th>所属数据库</th>
                    <th>包含角色</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;

    users.forEach(user => {
        const roles = user.roles.map(role =>
            `<span class="role-badge">${role.role}@${role.db}</span>`
        ).join('');

        tableHTML += `
            <tr>
                <td><strong>${user.username}</strong></td>
                <td>${user.database}</td>
                <td>${roles}</td>
                <td>
                    <button class="edit-btn" onclick="editUser('${user.username}', '${user.database}')" 
                            style="margin-right: 5px;">
                        编辑用户
                    </button>
                    <button class="remove-role-btn" onclick="deleteUser('${user.username}', '${user.database}')"
                            style="font-size: 12px; padding: 5px 8px;">
                        删除用户
                    </button>
                </td>
            </tr>
        `;
    });

    tableHTML += '</tbody></table>';
    contentDiv.innerHTML = tableHTML;
}

// 删除用户
async function deleteUser(username, database) {
    if (!confirm(`确定要删除用户 "${username}" 吗？此操作不可撤销！`)) {
        return;
    }

    try {
        const connectionSelect = document.getElementById('connectionSelect');
        const selectedConnectionId = connectionSelect.value;
        
        let url = '/api/users/delete';
        if (selectedConnectionId) {
            url += `?connection_id=${selectedConnectionId}`;
        }
        
        const response = await fetch(url, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                database: database,
                username: username
            })
        });
        
        const result = await response.json();
        
        if (response.ok && result.success) {
            alert('用户删除成功！');
            loadUsers(); // 刷新用户列表
        } else {
            alert(`删除失败: ${result.error || '未知错误'}`);
        }
    } catch (error) {
        alert(`删除失败: ${error.message}`);
    }
}

// 编辑用户
async function editUser(username, database) {
    // 设置当前编辑的用户信息
    currentEditUser = { username, database };
    
    // 填充表单
    document.getElementById('editUsername').value = username;
    document.getElementById('editTargetDatabase').value = database;
    document.getElementById('editNewPassword').value = '';
    document.getElementById('editConfirmPassword').value = '';
    
    // 清空角色容器
    document.getElementById('editRolesContainer').innerHTML = '';
    
    // 显示弹窗
    document.getElementById('editUserModal').style.display = 'block';
    
    // 加载用户当前角色
    await loadUserRoles(username, database);
    
    // 加载数据库选项到角色选择器
    await loadDatabaseOptionsForEdit();
}

// 关闭编辑用户弹窗
function closeEditUserModal() {
    document.getElementById('editUserModal').style.display = 'none';
    currentEditUser = null;
}

// 加载用户当前角色
async function loadUserRoles(username, database) {
    try {
        // 重置编辑角色计数器
        editRoleCounter = 0;
        
        const connectionSelect = document.getElementById('connectionSelect');
        const selectedConnectionId = connectionSelect.value;
        
        // 构建URL来获取用户角色信息
        let url = `/api/users/${encodeURIComponent(username)}/roles`;
        const params = new URLSearchParams();
        params.append('database', database);
        if (selectedConnectionId) {
            params.append('connection_id', selectedConnectionId);
        }
        url += '?' + params.toString();
        
        const response = await fetch(url);
        const result = await response.json();
        
        if (response.ok && result.roles) {
            // 显示当前角色
            if (result.roles.length > 0) {
                result.roles.forEach(role => {
                    addEditRoleItem(role.db, role.role);
                });
            } else {
                // 如果没有角色，添加一个空的角色项
                addEditRoleItem();
            }
        } else {
            console.error('加载用户角色失败:', result.error);
            // 添加一个空的角色项作为默认
            addEditRoleItem();
        }
    } catch (error) {
        console.error('加载用户角色失败:', error);
        // 添加一个空的角色项作为默认
        addEditRoleItem();
    }
}

// 添加编辑角色项
function addEditRoleItem(selectedDb = '', selectedRole = '') {
    editRoleCounter++;
    const container = document.getElementById('editRolesContainer');
    const roleItem = document.createElement('div');
    roleItem.className = 'role-item';
    roleItem.id = `edit-role-item-${editRoleCounter}`;
    
    roleItem.innerHTML = `
        <select name="editRoleDatabase" required>
            <option value="">选择数据库</option>
        </select>
        <select name="editRoleName" required>
            <option value="">选择角色</option>
            <option value="read">read (只读)</option>
            <option value="readWrite">readWrite (读写)</option>
            <option value="dbAdmin">dbAdmin (数据库管理)</option>
            <option value="userAdmin">userAdmin (用户管理)</option>
            <option value="dbOwner">dbOwner (数据库所有者)</option>
            <option value="readAnyDatabase">readAnyDatabase (读取任何数据库)</option>
            <option value="readWriteAnyDatabase">readWriteAnyDatabase (读写任何数据库)</option>
            <option value="userAdminAnyDatabase">userAdminAnyDatabase (管理任何数据库用户)</option>
            <option value="dbAdminAnyDatabase">dbAdminAnyDatabase (管理任何数据库)</option>
            <option value="clusterAdmin">clusterAdmin (集群管理)</option>
            <option value="root">root (超级管理员)</option>
        </select>
        <button type="button" class="remove-role-btn" onclick="removeEditRoleItem(${editRoleCounter})">删除</button>
    `;
    
    container.appendChild(roleItem);
    
    // 填充数据库选项
    loadDatabasesForEditRole(roleItem.querySelector('select[name="editRoleDatabase"]'), selectedDb);
    
    // 设置选中的角色
    if (selectedRole) {
        roleItem.querySelector('select[name="editRoleName"]').value = selectedRole;
    }
}

// 删除编辑角色项
function removeEditRoleItem(id) {
    const item = document.getElementById(`edit-role-item-${id}`);
    if (item) {
        item.remove();
    }
}

// 为编辑角色选择框加载数据库列表
async function loadDatabasesForEditRole(selectElement, selectedDb = '') {
    try {
        const connectionSelect = document.getElementById('connectionSelect');
        const selectedConnectionId = connectionSelect.value;
        
        let url = '/api/databases';
        if (selectedConnectionId) {
            url += `?connection_id=${selectedConnectionId}`;
        }
        
        const response = await fetch(url);
        const result = await response.json();
        
        if (response.ok && result.databases) {
            selectElement.innerHTML = '<option value="">选择数据库</option>';
            result.databases.forEach(db => {
                const option = document.createElement('option');
                option.value = db;
                option.textContent = db;
                if (db === selectedDb) {
                    option.selected = true;
                }
                selectElement.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载数据库列表失败:', error);
    }
}

// 为编辑弹窗加载数据库选项
async function loadDatabaseOptionsForEdit() {
    try {
        const connectionSelect = document.getElementById('connectionSelect');
        const selectedConnectionId = connectionSelect.value;

        let url = '/api/databases';
        if (selectedConnectionId) {
            url += `?connection_id=${selectedConnectionId}`;
        }

        const response = await fetch(url);
        const result = await response.json();

        if (response.ok && result.databases) {
            // 更新所有编辑角色选择器中的数据库选项
            updateEditRoleDatabaseOptions(result.databases);
        }
    } catch (error) {
        console.error('加载数据库列表失败:', error);
    }
}

// 更新编辑角色选择器中的数据库选项
function updateEditRoleDatabaseOptions(databases) {
    const roleItems = document.querySelectorAll('#editRolesContainer .role-item');
    roleItems.forEach(item => {
        const select = item.querySelector('select[name="editRoleDatabase"]');
        if (select) {
            const currentValue = select.value;
            select.innerHTML = '<option value="">选择数据库</option>';
            databases.forEach(db => {
                const option = document.createElement('option');
                option.value = db;
                option.textContent = db;
                if (db === currentValue) {
                    option.selected = true;
                }
                select.appendChild(option);
            });
        }
    });
}

// 登出功能
async function logout() {
    try {
        const response = await fetch('/api/logout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        const result = await response.json();
        
        if (result.success) {
            window.location.href = '/login';
        } else {
            alert('登出失败，请刷新页面重试');
        }
    } catch (error) {
        console.error('登出错误:', error);
        alert('登出失败，请刷新页面重试');
    }
}

// 加载用户信息
async function loadUserInfo() {
    try {
        const response = await fetch('/api/user/info');
        const result = await response.json();
        
        if (response.ok && result.user) {
            const userInfoDiv = document.getElementById('userInfo');
            const adminBadge = result.user.is_admin ? ' <span style="background: #28a745; color: white; padding: 2px 6px; border-radius: 10px; font-size: 12px;">管理员</span>' : '';
            userInfoDiv.innerHTML = `欢迎，${result.user.full_name || result.user.username}${adminBadge}`;
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
    }
}
// 加载数据库

//选项到选择框
async function loadDatabaseOptions() {
    try {
        // 获取选中的连接ID
        const connectionSelect = document.getElementById('connectionSelect');
        const selectedConnectionId = connectionSelect.value;

        // 构建URL，如果有选中的连接ID则添加参数
        let url = '/api/databases';
        if (selectedConnectionId) {
            url += `?connection_id=${selectedConnectionId}`;
            console.log(`使用选中的连接 ID: ${selectedConnectionId} 获取数据库列表`);
        } else {
            console.log('使用当前活跃连接获取数据库列表');
        }

        const response = await fetch(url);
        const result = await response.json();

        if (response.ok && result.databases) {
            const select = document.getElementById('databaseSelect');
            // 清空现有选项（保留"所有数据库"选项）
            select.innerHTML = '<option value="">所有数据库</option>';

            // 添加数据库选项
            result.databases.forEach(db => {
                const option = document.createElement('option');
                option.value = db;
                option.textContent = db;
                select.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载数据库列表失败:', error);
    }
}

// 新增用户相关功能

// 显示新增用户弹窗
function showAddUserModal() {
    const modal = document.getElementById('addUserModal');
    const databaseSelect = document.getElementById('databaseSelect');
    const targetDatabase = document.getElementById('targetDatabase');
    
    // 清空表单
    document.getElementById('addUserForm').reset();
    document.getElementById('rolesContainer').innerHTML = '';
    roleCounter = 0;
    
    // 复制数据库选项到目标数据库选择框
    targetDatabase.innerHTML = '<option value="">请选择数据库</option>';
    for (let i = 1; i < databaseSelect.options.length; i++) {
        const option = databaseSelect.options[i];
        const newOption = document.createElement('option');
        newOption.value = option.value;
        newOption.textContent = option.textContent;
        targetDatabase.appendChild(newOption);
    }
    
    // 如果当前有选中的数据库，设为默认值
    if (databaseSelect.value) {
        targetDatabase.value = databaseSelect.value;
    }
    
    // 添加一个默认角色
    addRoleItem();
    
    modal.style.display = 'block';
}

// 关闭新增用户弹窗
function closeAddUserModal() {
    document.getElementById('addUserModal').style.display = 'none';
}

// 添加角色项
function addRoleItem() {
    roleCounter++;
    const container = document.getElementById('rolesContainer');
    const roleItem = document.createElement('div');
    roleItem.className = 'role-item';
    roleItem.id = `role-item-${roleCounter}`;
    
    roleItem.innerHTML = `
        <select name="roleDatabase" required>
            <option value="">选择数据库</option>
        </select>
        <select name="roleName" required>
            <option value="">选择角色</option>
            <option value="read">read (只读)</option>
            <option value="readWrite">readWrite (读写)</option>
            <option value="dbAdmin">dbAdmin (数据库管理)</option>
            <option value="userAdmin">userAdmin (用户管理)</option>
            <option value="dbOwner">dbOwner (数据库所有者)</option>
            <option value="readAnyDatabase">readAnyDatabase (读取任何数据库)</option>
            <option value="readWriteAnyDatabase">readWriteAnyDatabase (读写任何数据库)</option>
            <option value="userAdminAnyDatabase">userAdminAnyDatabase (管理任何数据库用户)</option>
            <option value="dbAdminAnyDatabase">dbAdminAnyDatabase (管理任何数据库)</option>
            <option value="clusterAdmin">clusterAdmin (集群管理)</option>
            <option value="root">root (超级管理员)</option>
        </select>
        <button type="button" class="remove-role-btn" onclick="removeRoleItem(${roleCounter})">删除</button>
    `;
    
    container.appendChild(roleItem);
    
    // 填充数据库选项
    loadDatabasesForRole(roleItem.querySelector('select[name="roleDatabase"]'));
}

// 删除角色项
function removeRoleItem(id) {
    const item = document.getElementById(`role-item-${id}`);
    if (item) {
        item.remove();
    }
}

// 为角色选择框加载数据库列表
async function loadDatabasesForRole(selectElement) {
    try {
        const connectionSelect = document.getElementById('connectionSelect');
        const selectedConnectionId = connectionSelect.value;
        
        let url = '/api/databases';
        if (selectedConnectionId) {
            url += `?connection_id=${selectedConnectionId}`;
        }
        
        const response = await fetch(url);
        const result = await response.json();
        
        if (response.ok && result.databases) {
            selectElement.innerHTML = '<option value="">选择数据库</option>';
            result.databases.forEach(db => {
                const option = document.createElement('option');
                option.value = db;
                option.textContent = db;
                selectElement.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载数据库列表失败:', error);
    }
}

// 数据库管理功能
async function loadDatabases() {
    const contentDiv = document.getElementById('databasesContent');
    contentDiv.innerHTML = '<div class="loading">加载中...</div>';

    // 获取选中的连接ID
    const connectionSelect = document.getElementById('connectionSelect');
    const selectedConnectionId = connectionSelect.value;

    try {
        // 构建URL，如果有选中的连接ID则添加参数
        let url = '/api/databases';
        if (selectedConnectionId) {
            url += `?connection_id=${selectedConnectionId}`;
            console.log(`使用选中的连接 ID: ${selectedConnectionId} 获取数据库列表`);
        } else {
            console.log('使用当前活跃连接获取数据库列表');
        }

        const response = await fetch(url);
        const result = await response.json();

        if (response.ok && result.databases) {
            displayDatabases(result.databases);
        } else {
            contentDiv.innerHTML = `<div class="error">加载失败: ${result.error || '未知错误'}</div>`;
        }
    } catch (error) {
        contentDiv.innerHTML = `<div class="error">请求失败: ${error.message}</div>`;
    }
}

// 显示数据库列表
function displayDatabases(databases) {
    const contentDiv = document.getElementById('databasesContent');

    if (databases.length === 0) {
        contentDiv.innerHTML = '<div class="loading">没有找到数据库</div>';
        return;
    }

    let tableHTML = `
        <table class="table">
            <thead>
                <tr>
                    <th>数据库名称</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;

    databases.forEach(db => {
        // 系统数据库不允许删除
        const isSystemDb = ['admin', 'local', 'config'].includes(db);
        
        tableHTML += `
            <tr>
                <td><strong>${db}</strong></td>
                <td>
                    <button class="edit-btn" onclick="viewCollections('${db}')" 
                            style="margin-right: 5px;">
                        查看集合
                    </button>
                    ${!isSystemDb ? `
                        <button class="remove-role-btn" onclick="deleteDatabase('${db}')"
                                style="font-size: 12px; padding: 5px 8px;">
                            删除数据库
                        </button>
                    ` : '<span style="color: #666; font-size: 12px;">系统数据库</span>'}
                </td>
            </tr>
        `;
    });

    tableHTML += '</tbody></table>';
    contentDiv.innerHTML = tableHTML;
}

// 查看集合
function viewCollections(databaseName) {
    // 这里可以实现查看集合的功能
    alert(`查看数据库 "${databaseName}" 的集合功能待实现`);
}

// 删除数据库
async function deleteDatabase(databaseName) {
    if (!confirm(`确定要删除数据库 "${databaseName}" 吗？\n\n⚠️ 警告：此操作将永久删除数据库中的所有数据，且不可恢复！\n\n请输入数据库名称确认删除：`)) {
        return;
    }

    const confirmName = prompt(`请输入数据库名称 "${databaseName}" 以确认删除：`);
    if (confirmName !== databaseName) {
        alert('数据库名称不匹配，删除操作已取消。');
        return;
    }

    try {
        const connectionSelect = document.getElementById('connectionSelect');
        const selectedConnectionId = connectionSelect.value;
        
        let url = '/api/databases/delete';
        if (selectedConnectionId) {
            url += `?connection_id=${selectedConnectionId}`;
        }
        
        const response = await fetch(url, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                database_name: databaseName
            })
        });
        
        const result = await response.json();
        
        if (response.ok && result.success) {
            alert(`数据库 "${databaseName}" 删除成功！`);
            loadDatabases(); // 刷新数据库列表
            loadDatabaseOptions(); // 刷新数据库选择框
        } else {
            alert(`删除失败: ${result.error || '未知错误'}`);
        }
    } catch (error) {
        console.error('删除数据库失败:', error);
        alert(`删除失败: ${error.message}`);
    }
}

// 新建数据库相关功能

// 显示新建数据库弹窗
function showCreateDatabaseModal() {
    document.getElementById('createDatabaseModal').style.display = 'block';
    // 清空表单
    document.getElementById('createDatabaseForm').reset();
}

// 关闭新建数据库弹窗
function closeCreateDatabaseModal() {
    document.getElementById('createDatabaseModal').style.display = 'none';
}

// 连接选择变化处理
function onConnectionSelectChange() {
    const select = document.getElementById('connectionSelect');
    const selectedValue = select.value;

    // 清空数据显示，因为选择了不同的连接
    clearDataDisplays();

    // 清空连接状态显示
    const statusIndicator = document.getElementById('connectionStatus');
    const statusText = document.getElementById('connectionText');
    const environmentDiv = document.getElementById('currentEnvironment');
    const messageDiv = document.getElementById('connectionMessage');

    statusIndicator.className = 'status-indicator';
    statusText.textContent = '未连接';
    environmentDiv.textContent = '';
    messageDiv.innerHTML = '';

    if (selectedValue) {
        // 如果选择了特定连接，更新测试按钮文本
        const btn = document.getElementById('testConnectionBtn');
        btn.textContent = '测试选中连接';

        // 显示选择的连接信息
        const selectedOption = select.options[select.selectedIndex];
        messageDiv.innerHTML = `<div style="background: #e3f2fd; color: #1976d2; padding: 10px; border-radius: 5px; margin: 10px 0;">已选择连接: ${selectedOption.textContent}</div>`;
    } else {
        // 如果选择了默认选项，恢复原始文本
        const btn = document.getElementById('testConnectionBtn');
        btn.textContent = '测试连接';
    }
}

// 加载连接选项到下拉框
async function loadConnectionOptions() {
    try {
        const response = await fetch('/api/mongo-connections');
        const result = await response.json();

        if (response.ok && result.connections) {
            const select = document.getElementById('connectionSelect');
            // 清空现有选项
            select.innerHTML = '<option value="" selected>选择连接进行测试</option>';

            // 添加连接选项
            result.connections.forEach(conn => {
                const option = document.createElement('option');
                option.value = conn.id;
                option.textContent = `${conn.name} (${conn.host}:${conn.port})`;
                if (conn.is_active) {
                    option.textContent += ' - 当前环境';
                }
                select.appendChild(option);
            });

            // 确保默认选项被选中
            select.value = '';
        }
    } catch (error) {
        console.error('加载连接选项失败:', error);
    }
}

// 系统用户管理功能

// 加载系统用户列表
async function loadSystemUsers() {
    const contentDiv = document.getElementById('systemUsersContent');
    contentDiv.innerHTML = '<div class="loading">加载中...</div>';

    try {
        const response = await fetch('/api/system-users');
        const result = await response.json();

        if (response.ok && result.success) {
            displaySystemUsers(result.users);
        } else {
            contentDiv.innerHTML = `<div class="error">加载失败: ${result.error || '未知错误'}</div>`;
        }
    } catch (error) {
        contentDiv.innerHTML = `<div class="error">加载失败: ${error.message}</div>`;
    }
}

// 显示系统用户列表
function displaySystemUsers(users) {
    const contentDiv = document.getElementById('systemUsersContent');
    
    if (!users || users.length === 0) {
        contentDiv.innerHTML = '<div class="loading">暂无用户数据</div>';
        return;
    }

    // 获取当前用户信息
    getCurrentUserInfo().then(currentUserInfo => {
        const isAdmin = currentUserInfo && currentUserInfo.is_admin;
        const currentUserId = currentUserInfo ? currentUserInfo.id : null;

        let html = `
            <table class="table">
                <thead>
                    <tr>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>全名</th>
                        <th>角色</th>
                        <th>状态</th>
                        <th>最后登录</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
        `;

        users.forEach(user => {
            const isCurrentUser = user.id === currentUserId;
            const canEdit = isAdmin || isCurrentUser;
            const canDelete = isAdmin && !isCurrentUser;
            
            html += `
                <tr ${isCurrentUser ? 'class="current-user-row"' : ''}>
                    <td class="connection-name">
                        ${user.username}
                        ${isCurrentUser ? '<span style="color: #28a745; font-size: 12px;">(当前用户)</span>' : ''}
                    </td>
                    <td>${user.email || '-'}</td>
                    <td>${user.full_name || '-'}</td>
                    <td>
                        <span class="role-badge ${user.is_admin ? 'admin' : 'user'}">
                            ${user.is_admin ? '管理员' : '普通用户'}
                        </span>
                    </td>
                    <td>
                        <span class="status-badge ${user.is_active ? 'active' : 'inactive'}">
                            ${user.is_active ? '激活' : '禁用'}
                        </span>
                    </td>
                    <td>${user.last_login || '从未登录'}</td>
                    <td>${user.created_at}</td>
                    <td class="user-actions">
                        ${canEdit ? `<button class="edit-btn" onclick="showEditSystemUserModal(${user.id})">编辑</button>` : ''}
                        ${canDelete ? `<button class="remove-role-btn" onclick="deleteSystemUser(${user.id}, '${user.username}')">删除</button>` : ''}
                        ${!canEdit && !canDelete ? '<span style="color: #6c757d; font-size: 12px;">无权限</span>' : ''}
                    </td>
                </tr>
            `;
        });

        html += `
                </tbody>
            </table>
        `;

        if (!isAdmin) {
            html += '<div class="permission-note">注：普通用户只能查看和编辑自己的信息</div>';
        }

        contentDiv.innerHTML = html;
    });
}

// 获取当前用户信息
async function getCurrentUserInfo() {
    try {
        const response = await fetch('/api/user-info');
        const result = await response.json();
        return result.success ? result.user : null;
    } catch (error) {
        console.error('获取用户信息失败:', error);
        return null;
    }
}

// 显示修改密码弹窗
function showChangePasswordModal() {
    document.getElementById('changePasswordModal').style.display = 'block';
    document.getElementById('changePasswordForm').reset();
}

// 关闭修改密码弹窗
function closeChangePasswordModal() {
    document.getElementById('changePasswordModal').style.display = 'none';
}

// 显示个人信息弹窗
async function showProfileModal() {
    try {
        const response = await fetch('/api/user-info');
        const result = await response.json();

        if (response.ok && result.success && result.user) {
            const user = result.user;
            document.getElementById('profileUsername').value = user.username;
            document.getElementById('profileEmail').value = user.email || '';
            document.getElementById('profileFullName').value = user.full_name || '';
            document.getElementById('profileModal').style.display = 'block';
        } else {
            alert('获取用户信息失败');
        }
    } catch (error) {
        alert('获取用户信息失败: ' + error.message);
    }
}

// 关闭个人信息弹窗
function closeProfileModal() {
    document.getElementById('profileModal').style.display = 'none';
}

// 显示新增系统用户弹窗
function showCreateSystemUserModal() {
    document.getElementById('createSystemUserModal').style.display = 'block';
    document.getElementById('createSystemUserForm').reset();
}

// 关闭新增系统用户弹窗
function closeCreateSystemUserModal() {
    document.getElementById('createSystemUserModal').style.display = 'none';
}

// 显示编辑系统用户弹窗
async function showEditSystemUserModal(userId) {
    try {
        const response = await fetch('/api/system-users');
        const result = await response.json();

        if (response.ok && result.success) {
            const user = result.users.find(u => u.id === userId);
            if (user) {
                document.getElementById('editSystemUserId').value = user.id;
                document.getElementById('editSystemUsername').value = user.username;
                document.getElementById('editSystemEmail').value = user.email || '';
                document.getElementById('editSystemFullName').value = user.full_name || '';
                document.getElementById('editSystemIsActive').checked = user.is_active;
                document.getElementById('editSystemIsAdmin').checked = user.is_admin;
                document.getElementById('editSystemNewPassword').value = '';
                document.getElementById('editSystemUserModal').style.display = 'block';
            }
        } else {
            alert('获取用户信息失败');
        }
    } catch (error) {
        alert('获取用户信息失败: ' + error.message);
    }
}

// 关闭编辑系统用户弹窗
function closeEditSystemUserModal() {
    document.getElementById('editSystemUserModal').style.display = 'none';
}

// 删除系统用户
async function deleteSystemUser(userId, username) {
    if (!confirm(`确定要删除用户 "${username}" 吗？此操作不可恢复！`)) {
        return;
    }

    try {
        const response = await fetch(`/api/users/${userId}/delete`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const result = await response.json();

        if (response.ok && result.success) {
            alert(result.message);
            loadSystemUsers(); // 刷新用户列表
        } else {
            alert(`删除失败: ${result.error || '未知错误'}`);
        }
    } catch (error) {
        alert(`删除失败: ${error.message}`);
    }
}

// 页面加载时检查用户权限，隐藏/显示相应按钮
async function checkUserPermissions() {
    try {
        const userInfo = await getCurrentUserInfo();
        if (userInfo && !userInfo.is_admin) {
            const createUserBtn = document.getElementById('createUserBtn');
            if (createUserBtn) {
                createUserBtn.style.display = 'none';
            }
        }
    } catch (error) {
        console.log('获取用户信息失败:', error);
    }
}
// 连接管理功能

// 加载连接列表
async function loadConnections() {
    const contentDiv = document.getElementById('connectionsContent');
    contentDiv.innerHTML = '<div class="loading">加载中...</div>';

    try {
        const response = await fetch('/api/mongo-connections');
        const result = await response.json();

        if (response.ok && result.connections) {
            displayConnections(result.connections);
            // 同时更新连接选择框
            loadConnectionOptions();
        } else {
            contentDiv.innerHTML = `<div class="error">加载失败: ${result.error || '未知错误'}</div>`;
        }
    } catch (error) {
        contentDiv.innerHTML = `<div class="error">请求失败: ${error.message}</div>`;
    }
}

// 显示连接列表
function displayConnections(connections) {
    const contentDiv = document.getElementById('connectionsContent');

    if (connections.length === 0) {
        contentDiv.innerHTML = '<div class="loading">没有找到连接配置</div>';
        return;
    }

    let tableHTML = `
        <table class="table">
            <thead>
                <tr>
                    <th>连接信息</th>
                    <th>服务器详情</th>
                    <th>认证信息</th>
                    <th>连接状态</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;

    connections.forEach(conn => {
        const activeBadge = conn.is_active
            ? '<span class="status-badge active">当前环境</span>'
            : '<span class="status-badge inactive">非活跃</span>';

        const sslText = conn.use_ssl ? '启用SSL' : '无SSL';
        const rowClass = conn.is_active ? 'active-connection' : '';

        // 连接状态显示
        let connectionStatus = '';
        if (conn.status) {
            const statusIcon = `<span class="connection-status-icon ${conn.status}"></span>`;
            if (conn.status === 'success') {
                connectionStatus = `
                    <div>${statusIcon}连接正常</div>
                    ${conn.server_info ? `<div class="server-info">MongoDB ${conn.server_info.version} (${conn.server_info.databases_count} 个数据库)</div>` : ''}
                `;
            } else if (conn.status === 'error') {
                connectionStatus = `
                    <div>${statusIcon}连接失败</div>
                    <div class="error-info">${conn.message}</div>
                `;
            } else if (conn.status === 'testing') {
                connectionStatus = `<div>${statusIcon}测试中...</div>`;
            } else {
                connectionStatus = `<div><span class="connection-status-icon unknown"></span>未测试</div>`;
            }
        } else {
            connectionStatus = `<div><span class="connection-status-icon unknown"></span>未测试</div>`;
        }

        tableHTML += `
            <tr class="${rowClass}" id="connection-row-${conn.id}">
                <td>
                    <div class="connection-name">${conn.name}</div>
                    ${conn.is_active ? '<div class="connection-details">🔗 当前连接的环境</div>' : ''}
                    <div class="connection-details">${activeBadge}</div>
                </td>
                <td>
                    <div>${conn.host}:${conn.port}</div>
                    <div class="connection-details">${sslText}</div>
                </td>
                <td>
                    <div>用户: ${conn.username}</div>
                    <div class="connection-details">认证DB: ${conn.auth_database}</div>
                </td>
                <td id="status-${conn.id}">${connectionStatus}</td>
                <td>${conn.created_at}</td>
                <td>
                    <button class="test-btn" 
                            onclick="testSingleConnection(${conn.id})"
                            id="test-btn-${conn.id}">
                        测试连接
                    </button>
                    <button class="activate-btn" 
                            onclick="activateConnection(${conn.id})"
                            ${conn.is_active ? 'disabled' : ''}>
                        ${conn.is_active ? '当前环境' : '切换到此环境'}
                    </button>
                    <button class="edit-btn" onclick="editConnection(${conn.id})" 
                            style="margin-right: 5px;">
                        编辑
                    </button>
                    <button class="remove-role-btn" onclick="deleteConnection(${conn.id})"
                            style="font-size: 12px; padding: 5px 8px;"
                            ${conn.is_active ? 'disabled title="不能删除当前活跃连接"' : ''}>
                        删除
                    </button>
                </td>
            </tr>
        `;
    });

    tableHTML += '</tbody></table>';
    contentDiv.innerHTML = tableHTML;
}

// 激活连接
async function activateConnection(connectionId) {
    try {
        const response = await fetch(`/api/mongo-connections/${connectionId}/activate`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const result = await response.json();

        if (result.status === 'success') {
            // 显示成功消息
            const messageDiv = document.getElementById('connectionMessage');
            messageDiv.innerHTML = '<div class="success">连接切换成功！</div>';

            // 刷新连接列表和选择框
            loadConnections();
            loadConnectionOptions();

            // 清空连接选择框的选择，测试当前活跃连接
            const connectionSelect = document.getElementById('connectionSelect');
            connectionSelect.value = '';
            onConnectionSelectChange();

            // 测试新连接并更新环境信息
            testConnection();
        } else {
            alert(`切换失败: ${result.error || '未知错误'}`);
        }
    } catch (error) {
        alert(`请求失败: ${error.message}`);
    }
}

// 显示新增连接弹窗
function showAddConnectionModal() {
    document.getElementById('addConnectionModal').style.display = 'block';
    // 清空表单
    document.getElementById('addConnectionForm').reset();
    document.getElementById('connectionPort').value = '27017';
    document.getElementById('connectionAuthDb').value = 'admin';
}

// 关闭新增连接弹窗
function closeAddConnectionModal() {
    document.getElementById('addConnectionModal').style.display = 'none';
}

// 显示编辑连接弹窗
async function editConnection(connectionId) {
    currentEditConnectionId = connectionId;
    
    try {
        // 获取连接详情
        const response = await fetch(`/api/mongo-connections/${connectionId}`);
        const result = await response.json();
        
        if (response.ok && result.connection) {
            const conn = result.connection;
            
            // 填充表单
            document.getElementById('editConnectionId').value = conn.id;
            document.getElementById('editConnectionName').value = conn.name;
            document.getElementById('editConnectionHost').value = conn.host;
            document.getElementById('editConnectionPort').value = conn.port;
            document.getElementById('editConnectionUsername').value = conn.username;
            document.getElementById('editConnectionPassword').value = conn.password;
            document.getElementById('editConnectionAuthDb').value = conn.auth_database;
            document.getElementById('editConnectionSSL').checked = conn.use_ssl;
            document.getElementById('editConnectionActive').checked = conn.is_active;
            
            // 显示弹窗
            document.getElementById('editConnectionModal').style.display = 'block';
        } else {
            alert(`获取连接信息失败: ${result.error || '未知错误'}`);
        }
    } catch (error) {
        alert(`获取连接信息失败: ${error.message}`);
    }
}

// 关闭编辑连接弹窗
function closeEditConnectionModal() {
    document.getElementById('editConnectionModal').style.display = 'none';
    currentEditConnectionId = null;
}

// 删除连接
async function deleteConnection(connectionId) {
    try {
        // 先获取连接信息以显示确认信息
        const response = await fetch(`/api/mongo-connections/${connectionId}`);
        const result = await response.json();
        
        if (response.ok && result.connection) {
            const conn = result.connection;
            
            if (conn.is_active) {
                alert('不能删除当前活跃的连接！请先切换到其他连接。');
                return;
            }
            
            if (!confirm(`确定要删除连接 "${conn.name}" 吗？\n\n主机: ${conn.host}:${conn.port}\n用户: ${conn.username}\n\n此操作不可撤销！`)) {
                return;
            }
            
            // 执行删除
            const deleteResponse = await fetch(`/api/mongo-connections/${connectionId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            const deleteResult = await deleteResponse.json();
            
            if (deleteResponse.ok && deleteResult.success) {
                alert(`连接 "${conn.name}" 删除成功！`);
                loadConnections(); // 刷新连接列表
                loadConnectionOptions(); // 刷新连接选择框
            } else {
                alert(`删除失败: ${deleteResult.error || '未知错误'}`);
            }
        } else {
            alert(`获取连接信息失败: ${result.error || '未知错误'}`);
        }
    } catch (error) {
        alert(`删除失败: ${error.message}`);
    }
}

// 测试单个连接
async function testSingleConnection(connectionId) {
    const statusCell = document.getElementById(`status-${connectionId}`);
    const testBtn = document.getElementById(`test-btn-${connectionId}`);

    // 更新状态为测试中
    statusCell.innerHTML = '<div><span class="connection-status-icon testing"></span>测试中...</div>';
    testBtn.disabled = true;
    testBtn.textContent = '测试中...';

    try {
        const response = await fetch(`/api/mongo-connections/${connectionId}/test`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const result = await response.json();

        if (result.status === 'success') {
            statusCell.innerHTML = `
                <div><span class="connection-status-icon success"></span>连接正常</div>
                ${result.server_info ? `<div class="server-info">MongoDB ${result.server_info.version} (${result.server_info.databases_count} 个数据库)</div>` : ''}
            `;
        } else {
            statusCell.innerHTML = `
                <div><span class="connection-status-icon error"></span>连接失败</div>
                <div class="error-info">${result.message}</div>
            `;
        }
    } catch (error) {
        statusCell.innerHTML = `
            <div><span class="connection-status-icon error"></span>测试失败</div>
            <div class="error-info">请求错误: ${error.message}</div>
        `;
    }

    testBtn.disabled = false;
    testBtn.textContent = '测试连接';
}

// 测试所有连接
async function testAllConnections() {
    const contentDiv = document.getElementById('connectionsContent');

    // 显示加载状态
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'loading';
    loadingDiv.textContent = '正在测试所有连接...';
    contentDiv.insertBefore(loadingDiv, contentDiv.firstChild);

    try {
        const response = await fetch('/api/mongo-connections/test-all');
        const result = await response.json();

        // 移除加载提示
        loadingDiv.remove();

        if (response.ok && result.connections) {
            displayConnections(result.connections);

            // 显示测试结果摘要
            const successCount = result.connections.filter(conn => conn.status === 'success').length;
            const totalCount = result.connections.length;

            const messageDiv = document.getElementById('connectionMessage');
            if (successCount === totalCount) {
                messageDiv.innerHTML = `<div class="success">所有 ${totalCount} 个连接测试完成，全部连接正常！</div>`;
            } else {
                messageDiv.innerHTML = `<div class="error">连接测试完成：${successCount}/${totalCount} 个连接正常</div>`;
            }
        } else {
            loadingDiv.textContent = `测试失败: ${result.error || '未知错误'}`;
            loadingDiv.className = 'error';
        }
    } catch (error) {
        loadingDiv.textContent = `请求失败: ${error.message}`;
        loadingDiv.className = 'error';
    }
}